<template>
	<div class="echart_box">
		<div class="echart" id="mychart" ref="mychart" style="width:100%; height: 200px;"></div>
		<div class="back" :style="`--timeWidth: ${timeWidth}px`" @click="back" v-if="showBack">
			<i class="el-icon-right"></i>
		</div>
		<!-- <div @click="testMyOrder()">get</div> -->
		<!-- <div @click="testAdd()">add</div> -->
	</div>
</template>

<script>
	// import * as echarts from "echarts";
	// import * as am5 from "@amcharts/amcharts5";
	// import * as am5xy from "@amcharts/amcharts5/xy";
	// import * as am5stock from "@amcharts/amcharts5/stock";
	// import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
	// import {
	// 	createChart
	// } from 'lightweight-charts';
	import {
		createWebSocket,
		sendSock,
		closeSock
	} from "@/utils/websocket";
	import {
		marketTickHistory,
		marketHistoryKline
	} from '@/api/home'
	export default {
		props: {},
		components: {},
		data() {
			return {
				chart: null,
				areaSeries: null,
				loading: false,
				showBack: false,
				acTick: 1, // 1tick 2烛台
				markSize: 5,
				myToolTip: {
					width: 66,
					height: 50,
					margin: 6,
				},
				timeWidth: 0,
				orderInfo: {},
				// time: 1709179200000,
				// time: 1709136000000,
				tickObj: { // 长连接 period 对应的推送
					Tick: 'Tick',
					'1m': '1min',
					'5m': '5min',
					'1h': '1hour',
					'4h': '4hour',
					'1d': '1day',
				},
				valueSeries: {},
				newSeries: {}, // 最新一期
				dataSeries: [],
				toolTipList: [], // 用户下单显示的dom 
				myToolTipList: [], // 自己下单显示的dom 
				lastObj: {}, // 测试用
				initEchartsData: [
					// {
					// 	"value": "67213.74444",
					// 	"time": 1709868866000
					// },
					// {
					// 	"value": "67213.89589",
					// 	"time": 1709868867000
					// },
					// {
					// 	"value": "67213.80812",
					// 	"time": 1709868868000
					// },
					// {
					// 	"value": "67213.78574",
					// 	"time": 1709868869000
					// },
					// {
					// 	"value": "67213.87527",
					// 	"time": 1709868870000
					// },
					// {
					// 	"value": "67213.74857",
					// 	"time": 1709868871000
					// },
					// {
					// 	"value": "67213.82196",
					// 	"time": 1709868872000
					// },
					// {
					// 	"value": "67208.67033",
					// 	"time": 1709868873000
					// },
					// {
					// 	"value": "67208.98671",
					// 	"time": 1709868874000
					// },
					// {
					// 	"value": "67208.63177",
					// 	"time": 1709868875000
					// },
					// {
					// 	"value": "67196.19434",
					// 	"time": 1709868876000
					// },
					// {
					// 	"value": "67196.54461",
					// 	"time": 1709868877000
					// },
					// {
					// 	"value": "67196.29005",
					// 	"time": 1709868878000
					// },
					// {
					// 	"value": "67196.20232",
					// 	"time": 1709868879000
					// },
					// {
					// 	"value": "67196.16934",
					// 	"time": 1709868880000
					// },
					// {
					// 	"value": "67196.95055",
					// 	"time": 1709868881000
					// },
					// {
					// 	"value": "67196.02484",
					// 	"time": 1709868882000
					// },
					// {
					// 	"value": "67196.35831",
					// 	"time": 1709868883000
					// },
					// {
					// 	"value": "67196.34579",
					// 	"time": 1709868884000
					// },
					// {
					// 	"value": "67196.63611",
					// 	"time": 1709868885000
					// },
					// {
					// 	"value": "67196.23944",
					// 	"time": 1709868886000
					// },
					// {
					// 	"value": "67196.81174",
					// 	"time": 1709868887000
					// },
					// {
					// 	"value": "67196.19187",
					// 	"time": 1709868888000
					// },
					// {
					// 	"value": "67196.32385",
					// 	"time": 1709868889000
					// },
					// {
					// 	"value": "67196.34081",
					// 	"time": 1709868890000
					// },
					// {
					// 	"value": "67196.19955",
					// 	"time": 1709868891000
					// },
					// {
					// 	"value": "67196.86629",
					// 	"time": 1709868892000
					// },
					// {
					// 	"value": "67196.44774",
					// 	"time": 1709868893000
					// },
					// {
					// 	"value": "67196.26296",
					// 	"time": 1709868894000
					// },
					// {
					// 	"value": "67196.15913",
					// 	"time": 1709868895000
					// }
				], // 初始化数据
			}
		},
		computed: {
			matches() {
				return this.$store.state.matches
			},
			userInfo() {
				return this.$store.state.userInfo
			},
			newOrderPrice() {
				return this.$store.state.newOrderPrice
			},
			closeMyDownOrder() {
				return this.$store.state.closeMyDownOrder
			},
			tick() {
				return this.$store.state.tick
			},
			webSocketStatus() {
				return this.$store.state.webSocketStatus
			},
			timeDown() {
				return this.$store.state.timeDown
			}
		},
		watch: {
			timeDown() {
				// this.areaSeries?.update(this.newSeries);
			},
			newOrderPrice(val, oldval) {
				// console.log('val', val, oldval);
				if (val && oldval) {
					if (this.tick == 'Tick') {
						if (val.price > oldval.price) {
							this.setPriceLineColor(1)
						} else {
							this.setPriceLineColor(2)
						}
					} else {
						if (val.close > oldval.close) {
							this.setPriceLineColor(1)
						} else {
							this.setPriceLineColor(2)
						}
					}

				}
			},
			closeMyDownOrder(val) {
				if (val) {
					const container = document.getElementById('mychart');
					const tdElement = document.querySelector(
						'#mychart .tv-lightweight-charts table tr:first-child td:nth-child(2) div');
					var children = tdElement.children;
					for (var item of children) {
						if (item.id == val.timestamp) {
							tdElement.removeChild(item);
						}
					}
				}
			},
			tick(val) {
				this.changeTick(val)
			},
			// 拿到交易对id 再去请求历史数据
			matches(val) {
				if (val) {
					this.init()
					this.showBack = false
				}
			}
		},
		async mounted() {
			// createWebSocket(this.webSocket);
			if (this.matches) {
				this.$nextTick(() => {
					this.init()
				})
			}
		},
		methods: {
			async init() {
				let tick = localStorage.getItem('Tick')
				if (tick && tick != 'Tick') {
					await this.getListK()
					this.initEcharts2()
					this.acTick = 2
				} else {
					await this.getList()
					this.initEcharts();
					this.acTick = 1
				}
			},
			webSocket(data) {
				// console.log('data', data);
				if (data && data.type == 'open') {
					// if (this.acTick == 1) {
					// 折线图的订阅
					sendSock(JSON.stringify({
						type: 'sub',
						params: "GLOBAL_TX.BTC/USDT"
					}))
					// } else {
					// 烛台图的订阅
					sendSock(JSON.stringify({
						type: 'sub',
						params: "KLINE.BTC/USDT"
					}))
					// }
					sendSock(JSON.stringify({
						type: 'sub',
						params: "TRADE.BTC/USDT"
					}))
					sendSock(JSON.stringify({
						type: 'sub',
						params: "ODDS.BTC/USDT"
					}))
				}
				if (data && data.type == 'close') {
					console.log('关闭了链接');
					this.$store.commit('onChangeWebSocketStatus', false)
					if (this.$route.path == '/') {
						setTimeout(() => {
							createWebSocket(this.webSocket);
						}, 1000)
					}
				}
				if (data && data.type == 'sub_result') {
					console.log('订阅成功开启了链接');
					this.$store.commit('onChangeWebSocketStatus', true)
				}
				if (data && data.type == "KLINE") {
					// console.log('KLINE', data);
					if (this.acTick == 2) {
						// console.log('!!!!!!!!!!!!!!!!!!', data.kline.period, this.tickObj[this.tick], this.tickObj, this.tick);
						if (data.kline.period == this.tickObj[this.tick]) {
							this.newSeries = {
								...data.kline,
								oldTime: data.kline.time,
								time: data.kline.time / 1000,
							}
							// this.$nextTick(() => {
							// 1min 5min 1hour 1day
							this.areaSeries?.update(this.newSeries);
							// 缓存最新的 用于获取x ,y 值
							this.$store.commit('upDataNewOrderPrice', this.newSeries)
							// })
						}
					}
					if (data.kline.period == '1min') {
						this.$store.commit('upDataOneMinPrice', {
							...data.kline,
							oldTime: data.kline.time,
							time: data.kline.time / 1000,
						})
					}
				}
				if (data && data.type == "GLOBAL_TX") {
					if (this.acTick == 1) {
						let obj = data.completes[0]
						this.newSeries = {
							...obj,
							time: obj.timestamp,
							value: obj.price
						}
						// this.$nextTick(() => {
						// console.log('newSeries::', this.newSeries);
						this.areaSeries?.update(this.newSeries || {});
						// this.areaSeries?.setMarkers([{
						// 	time: obj.timestamp,
						// 	position: "inBar",
						// 	color: '#f68410',
						// 	shape: 'circle',
						// 	size: 1,
						// }]);
						// 缓存最新的 用于获取x ,y 值
						this.$store.commit('upDataNewOrderPrice', this.newSeries)
						// })
					}
					this.$store.commit('upDataTickPrice', {
						...data.completes[0],
						time: data.completes[0].timestamp,
						value: data.completes[0].price
					})
				}
				if (data && data.type == "TRADE") {
					if (this.toolTipList.length <= 3) {
						if (data.trade.uid == this.userInfo.id) {
							// console.log('自己下单了：：：：：', data);
							this.createMyOrder(data.trade)
						} else {
							// console.log('有人下单了：：：：：', data);
							this.createOrder(data.trade)
						}
					}
				}
				if (data && data.type == "ODDS") {
					this.$store.commit('upDataOdd', data.odds)
					this.$store.commit('onChangeTips', 3)
				}
			},
			async getList(lastTime) {
				if (this.loading) return
				this.loading = true
				let startTime = this.$day().subtract(30, 'second').valueOf() / 1000
				let endTime = this.$day().valueOf() / 1000
				if (lastTime) {
					// console.log('lastTime11111:', startTime, endTime);
					startTime = this.$day(lastTime).subtract(30, 'second').valueOf() / 1000
					endTime = this.$day(lastTime).subtract(1, 'second').valueOf() / 1000
					// console.log('lastTime2222:', startTime, endTime);
				}
				const res = await marketTickHistory({
					match_id: this.matches.id,
					startTime: startTime,
					endTime: endTime,
				})
				if (res && res.code == 1) {
					let newArr = res.data.map(i => {
						return {
							...i,
							time: i.timestamp,
							value: i.price
						}
					})
					// 有lastTime 代表拿老数据
					if (lastTime) {
						this.initEchartsData = [...newArr, ...this.initEchartsData]
						this.areaSeries.setData(this.initEchartsData);
						// console.log('@@@@', this.initEchartsData, );
						// this.valueSeries.data.setAll(this.initEchartsData);
					} else {
						this.initEchartsData = newArr
					}
				}
				this.$nextTick(() => {
					this.loading = false
				})
				// console.log('tickRes::::', res);
			},
			async getListK(lastTime) {
				if (this.loading) return
				this.loading = true
				let startTime;
				let endTimeN;
				if (this.tick == '1m') {
					startTime = this.$day(lastTime ? lastTime * 1000 : new Date()).subtract(30, 'minute').valueOf();
				} else if (this.tick == '5m') {
					startTime = this.$day(lastTime ? lastTime * 1000 : new Date()).subtract(150, 'minute').valueOf();
				} else if (this.tick == '1h') {
					startTime = this.$day(lastTime ? lastTime * 1000 : new Date()).subtract(30, 'hour').valueOf();
				} else if (this.tick == '4h') {
					startTime = this.$day(lastTime ? lastTime * 1000 : new Date()).subtract(120, 'hour').valueOf();
				} else if (this.tick == '1d') {
					startTime = this.$day(lastTime ? lastTime * 1000 : new Date()).subtract(30, 'day').valueOf();
					endTimeN = lastTime ? lastTime * 1000 : this.$day().subtract(1, 'day').valueOf();
				}
				// console.log('^^^^^^^^^^', {
				// 	currency_match_id: this.matches.id,
				// 	period: this.tickObj[this.tick],
				// 	startTime: startTime,
				// 	endTime: endTimeN ? endTimeN : this.$day().valueOf(),
				// });
				// if (lastTime) return
				const res = await marketHistoryKline({
					currency_match_id: this.matches.id,
					period: this.tickObj[this.tick],
					startTime: startTime,
					endTime: lastTime ? lastTime * 1000 : endTimeN ? endTimeN : this.$day().valueOf(),
				}).catch(err => this.loading = false)
				if (res && res.code == 1) {
					let newArr = Object.values(res.data).map(i => {
						return {
							...i,
							time: i.time / 1000
						}
					})
					// 有lastTime 代表拿老数据
					if (lastTime) {
						// 删除重复的一项
						newArr.pop()
						this.initEchartsData = [...newArr, ...this.initEchartsData]
						this.areaSeries.setData(this.initEchartsData);
					} else {
						this.initEchartsData = newArr
					}
				}
				this.$nextTick(() => {
					this.loading = false
				})
				// console.log('res:::', res, this.initEchartsData);
			},
			async changeTick(val) {
				this.chart.remove()
				if (val != 'Tick') {
					await this.getListK()
					this.initEcharts2();
					this.acTick = 2
				} else {
					await this.getList()
					this.initEcharts()
					this.acTick = 1
				}
				// console.log('acTick', this.acTick);
			},

			getNearestSecond5(date) {
				const seconds = date.getSeconds();
				const lastDigit = seconds % 10; // 获取秒数的个位数
				if (seconds === 59) {
					// 如果秒数为59，则进到下一分钟
					date.setSeconds(0);
					date.setMinutes(date.getMinutes() + 1);
				} else if (lastDigit === 1 || lastDigit === 9) {
					// 如果个位数是1或9，则调整为0
					if (lastDigit === 9) {
						date.setSeconds(date.getSeconds() + 1);
					} else {
						date.setSeconds(seconds - lastDigit);
					}
				} else if (lastDigit === 4 || lastDigit === 6) {
					// 如果个位数是4或6，则调整为5
					date.setSeconds(seconds - lastDigit + 5);
				}
				return date;
			},
			customFormatter(time, tickMarkType, locale) {
				// console.log('time', time, tickMarkType, locale);
				if (this.newTime == time) return ''
				this.newTime = time
				if (this.acTick == 2) {
					// console.log('time', time);
					let newTime = time * 1000
					if (this.tick == '1m') {
						return this.$day(newTime).format('HH:mm:ss');
					} else if (this.tick == '1d') {
						return this.$day(newTime).format('YYYY-MM-DD');
					} else {
						return this.$day(newTime).format('MM-DD HH:mm');
					}
				} else {
					// const date = new Date(time); // 将 UNIX 时间戳转换为 JavaScript 时间对象
					// const hours = date.getHours().toString().padStart(2, '0'); // 获取小时并补零
					// const minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟并补零
					// // const adjustedDate = this.getNearestSecond5(date).toString();
					// const seconds = this.$day(time).format('ss'); // 获取秒数并补零
					// if (seconds % 5 === 0) {
					// return `${hours}:${minutes}:${seconds}`; // 返回自定义格式的时间字符串
					return this.$day(time).format('HH:mm:ss'); // 返回自定义格式的时间字符串
					// } else {
					// 	return ''
					// }
				}
			},
			CustomPriceFormatter(val) {
				let str = val;
				// console.log('val2', val2);
				if (typeof str === 'string') {
					str = parseFloat(str); // 将字符串转换为数值类型
				}
				if (typeof str === 'number') {
					if (isNaN(str)) {
						// 处理无效数值的情况
						console.error('Invalid number');
					} else {
						if (Number.isInteger(str)) {
							const desiredWidth = 13;
							const formattedPrice = str.toFixed(2); // 格式化价格到小数点后两位  
							const priceString = formattedPrice.toString();
							const padding = ' '.repeat(Math.max(0, desiredWidth - priceString.length)); // 计算并添加空格 
							// console.log('padding', padding, priceString.length);
							// 整数的情况
							str = `${padding}${str.toFixed(2)}`;
						} else {
							if (this.areDecimalsSame(str)) {
								str = str.toFixed(2);
							} else {
								// 非整数的情况
								str = str.toFixed(5);
							}
						}
					}
				} else {
					// 处理非数值的情况
					console.error('Not a number');
				}

				// console.log('str', str);
				return str
			},
			initEcharts() {
				let root = am5.Root.new(this.$refs.mychart);
				console.log('root', root, am5);
				root.setThemes([am5themes_Animated.new(root)]);
				var easing = am5.ease.linear;

				let stockChart = root.container.children.push(
					am5stock.StockChart.new(root, {
						focusable: true,
						// wheelX: "panX",
						// wheelY: "zoomX",
						panX: true,
						panY: true,
						pinchZoomX: true,
						paddingRight: 0,
						minDistance: 5,
						// layout: root.verticalLayout
					})
				);

				// Define data
				let data = this.initEchartsData.map(i => {
					return {
						...i,
						value: i.value - 0
					}
				})

				var mainPanel = stockChart.panels.push(am5stock.StockPanel.new(root, {
					focusable: true,
					// wheelX: "panX",
					// wheelY: "zoomX",
					panX: true,
					panY: true,
					pinchZoomX: true,
				}));

				console.log('mainPanel', mainPanel, stockChart);


				// Create X-Axis
				let xAxis = mainPanel.xAxes.push(
					am5xy.DateAxis.new(root, {
						// maxDeviation: 10,
						// minZoomCount: 3,
						// maxZoomCount: 10,
						groupData: false,
						extraMax: 0.1,
						// extraMax: 0.1, // this adds some space in front
						// extraMin: -0.1, // this removes some space form th beginning so that the line would not be cut off
						// autoZoom: false,
						start: 0.5,
						baseInterval: {
							timeUnit: "second",
							count: 1
						},
						renderer: am5xy.AxisRendererX.new(root, {
							minorGridEnabled: true,
							minGridDistance: 50,
							cellStartLocation: 0.2,
							cellEndLocation: 0.8
						}),
						// categoryField: "time"
					})
				);
				var xRenderer = xAxis.get("renderer");

				xRenderer.grid.template.setAll({
					visible: false,
				})

				// xAxis.data.setAll(data);

				let yAxis = mainPanel.yAxes.push(
					am5xy.ValueAxis.new(root, {
						// extraTooltipPrecision: 2,
						// extraMax: 0.1,
						// treatZeroAs: 0.000001,
						renderer: am5xy.AxisRendererY.new(root, {})
					})
				);

				var yRenderer = yAxis.get("renderer");
				yRenderer.grid.template.setAll({
					// visible: false,
					strokeOpacity: 0,
					strokeWidth: 1
				})


				// Create series
				let valueSeries = mainPanel.series.push(
					am5xy.SmoothedXYLineSeries.new(root, {
						name: "Series",
						xAxis: xAxis,
						yAxis: yAxis,
						valueYField: "value",
						valueXField: "time",
						stacked: false,
						stroke: am5.color("#0091FF")
					})
				);
				this.valueSeries = valueSeries;

				valueSeries.fills.template.set("fillGradient", am5.LinearGradient.new(root, {
					stops: [{
						color: am5.color(0x002AFF),
						opacity: 0.3
					}, {
						color: am5.color(0x137EFE),
						opacity: 0
					}],
					rotation: 90
				}));

				valueSeries.fills.template.setAll({
					visible: true,
					fillOpacity: 1
				});

				valueSeries.strokes.template.setAll({
					strokeWidth: 2
				});

				// 价格线
				var currentValueDataItem = yAxis.createAxisRange(yAxis.makeDataItem({
					value: 0
				}));

				var currentLabel = currentValueDataItem.get("label");
				if (currentLabel) {
					currentLabel.setAll({
						visible: true,
						strokeWidth: 10,
						fill: am5.color(0xffffff),
						background: am5.Rectangle.new(root, {
							fill: am5.color(0x000000)
						})
					})
				}

				var currentGrid = currentValueDataItem.get("grid");
				if (currentGrid) {
					currentGrid.setAll({
						strokeOpacity: 0.5,
						strokeDasharray: [2, 5]
					});
				}


				// valueSeries.columns.template.set("fillGradient", am5.LinearGradient.new(root, {
				// 	stops: [{
				// 		color: am5.color(0xff621f),
				// 		opacity: 1
				// 	}, {
				// 		color: am5.color(0x946b49),
				// 		opacity: 0.2
				// 	}]
				// }));


				// console.log('data', data);
				data[data.length - 1].bullet = true;
				valueSeries.data.setAll(data);

				// var now = new Date(data.time);
				// var minDate = new Date(now.getTime() - 1 * 60 * 1000); // 1 minutes ago
				// var maxDate = now;

				// xAxis.set("min", minDate.getTime());
				// xAxis.set("max", maxDate.getTime());

				valueSeries.bullets.push(function(root, series, dataItem) {
					// only create sprite if bullet == true in data context
					if (dataItem.dataContext.bullet) {
						var container = am5.Container.new(root, {});
						var circle0 = container.children.push(am5.Circle.new(root, {
							radius: 3,
							fill: am5.color(0x0091FF)
						}));
						var circle1 = container.children.push(am5.Circle.new(root, {
							radius: 3,
							fill: am5.color(0x0091FF)
						}));

						circle1.animate({
							key: "radius",
							to: 20,
							duration: 1000,
							easing: am5.ease.out(am5.ease.cubic),
							loops: Infinity
						});
						circle1.animate({
							key: "opacity",
							to: 0,
							from: 1,
							duration: 1000,
							easing: am5.ease.out(am5.ease.cubic),
							loops: Infinity
						});

						return am5.Bullet.new(root, {
							locationX: undefined,
							sprite: container
						})
					}
				})

				// var cursor = mainPanel.set("cursor", am5xy.XYCursor.new(root, {
				// 	xAxis: xAxis
				// }));
				// cursor.lineY.set("visible", false);

				// valueSeries.events.once("datavalidated", function(ev) {
				// 	console.log('evvv', ev);
				// 	// ev.target.get("xAxis").zoomToDates(new Date(2021, 0, 1), new Date(2022, 0, 1));
				// });
				// xAxis.zoom(0.5, 1)
				console.log('xAxis', xAxis);
				xAxis.events.on('positionchanged', (ev) => {
					console.log('变化了', ev);
				})

				var endPoint, startPoint;
				// console.log('valueSeries', mainPanel.plotContainer);
				valueSeries.events.on('dragged', (ev) => {
					console.log('拖动了');
				}, this)

				mainPanel.plotContainer.events.on('pointerdown', (ev) => {
					// let ad = xAxis.getSeriesItem(ev.point.x)
					startPoint = {
						x: ev.point.x,
						y: ev.point.y
					};
					console.log('摁下', ev);
				})

				mainPanel.plotContainer.events.on('pointerup', (ev) => {
					var timeDate = xAxis.positionToDate(xAxis.toAxisPosition(xAxis.coordinateToPosition(ev.point.x)));
					endPoint = {
						x: ev.point.x,
						y: ev.point.y
					};
					if (endPoint.x > startPoint.x) {
						console.log("向右滑动");
					} else {
						console.log("向左滑动");
					}
					console.log('抬起', timeDate.getTime(), valueSeries.data.getIndex(0));
				})


				console.log('执行完了？');

			},
			initEcharts2() {
				document.getElementById("mychart").innerHTML = ''
				const chartOptions = {
					layout: {
						background: {
							color: '#161D26'
						},
						textColor: '#8B8D98'
					},
					LineData: {
						color: '#161D26'
					},
					grid: {
						vertLines: {
							visible: false,
						},
						horzLines: {
							visible: false,
						}
					},
					timeScale: {
						timeVisible: true,
						tickMarkFormatter: this.customFormatter,
						minBarSpacing: 15,
						barSpacing: 0,
					},
					localization: {
						type: 'custom',
						priceFormatter: this.CustomPriceFormatter, // 自定义价格格式化器
						minMove: 0.000001
					},
				};

				this.chart = createChart(document.getElementById("mychart"), chartOptions);
				this.chart.timeScale().subscribeVisibleTimeRangeChange(this.myVisibleTimeRangeChangeHandler);
				// this.chart.subscribeCrosshairMove(this.subscribeCrosshairMove);
				this.areaSeries = this.chart.addCandlestickSeries({
					upColor: '#26a69a',
					downColor: '#ef5350',
					priceFormat: {
						precision: 2,
						minMove: 0.000001,
					},
				});
				this.areaSeries.setData(this.initEchartsData);
				this.timeWidth = this.chart.timeScale().width()
				this.chart.timeScale().fitContent();
			},
			setPriceLineColor(type) {
				this.areaSeries?.applyOptions({
					priceLineColor: type == 1 ? '#2ECC71' : '#FF5449', // 修改价格线颜色为红色
				});

			},

			myVisibleTimeRangeChangeHandler(newVisibleTimeRange) {
				if (this.toolTipList.length > 0) {
					const container = document.getElementById('mychart');
					const tdElement = document.querySelector(
						'#mychart .tv-lightweight-charts table tr:first-child td:nth-child(2) div');
					var children = tdElement.children;
					for (var item of children) {
						let find = this.toolTipList.find(i => i == item.id)
						if (find) {
							const chartBounds = this.chart.timeScale().getVisibleRange();
							const xCoordinate = this.chart.timeScale().timeToCoordinate(Number(item.id), chartBounds) - 33
							const coordinate = this.areaSeries.priceToCoordinate(Number(item.getAttribute('price')));
							const toolTipHeight = 70;
							const coordinateY =
								coordinate - toolTipHeight > 0 ?
								coordinate - toolTipHeight :
								Math.max(
									0,
									Math.min(
										container.clientHeight - toolTipHeight,
										coordinate
									)
								);
							if (coordinate - toolTipHeight > 0) {
								const div = item.querySelector('div')
								div.className = 'otherOrder_el'
								item.style.top = coordinateY + 'px';
							} else {
								const div = item.querySelector('div')
								div.className = 'otherOrder_el2'
								item.style.top = coordinateY + 5 + 'px';
							}
							// console.log('find', xCoordinate, item.id / 1000);
							item.style.left = xCoordinate + 'px';
							// item.style.top = coordinateY + 'px';
						}
					}
					// console.log('children', children, this.toolTipList);
					// this.toolTipList.map(i => {
					// 	container.children
					// })
					// let x = this.chart.timeScale().timeToCoordinate(1642425322)
				}

				if (this.myToolTipList.length > 0) {
					const container = document.getElementById('mychart');
					const tdElement = document.querySelector(
						'#mychart .tv-lightweight-charts table tr:first-child td:nth-child(2) div');
					var children = tdElement.children;
					for (var item of children) {
						let find = this.myToolTipList.find(i => i == item.id)
						if (find) {
							const chartBounds = this.chart.timeScale().getVisibleRange();
							const xCoordinate = this.chart.timeScale().timeToCoordinate(Number(item.id), chartBounds) - 33
							const coordinate = this.areaSeries.priceToCoordinate(Number(item.getAttribute('price')));
							const toolTipWidth = this.myToolTip.width;
							const toolTipHeight = this.myToolTip.height;
							const toolTipMargin = this.myToolTip.margin;
							// const coordinateY = coordinate > 70 ? coordinate - 50 : coordinate
							// if (coordinate > 70) {
							// 	const div = item.querySelector('div')
							// 	div.className = 'myOrder_el'
							// } else {
							// 	const div = item.querySelector('div')
							// 	div.className = 'myOrder2_el'
							// }
							const coordinateY =
								coordinate - toolTipHeight > 0 ?
								coordinate - toolTipHeight :
								Math.max(
									0,
									Math.min(
										container.clientHeight - toolTipHeight,
										coordinate
									)
								);
							if (coordinate - toolTipHeight > 0) {
								const div = item.querySelector('div')
								div.className = 'myOrder_el'
								item.style.top = coordinateY + 12 + 'px';
							} else {
								const div = item.querySelector('div')
								div.className = 'myOrder2_el'
								item.style.top = coordinateY - 12 + 'px';
							}
							// console.log('find::', coordinate, coordinateY);
							item.style.left = xCoordinate + 'px';
						}
					}
				}
				// console.log('newVisibleTimeRange', newVisibleTimeRange.from, this.initEchartsData[0].time);
				// this.newToTime = newVisibleTimeRange.to
				if (newVisibleTimeRange.from == this.initEchartsData[0].time) {
					// console.log('加载更多');
					if (this.acTick == 1) {
						this.getList(this.initEchartsData[0].time)
					} else {
						this.getListK(this.initEchartsData[0].time)
					}
				}

				if (newVisibleTimeRange.to != this.newSeries.time && this.webSocketStatus) {
					this.showBack = true;
				} else {
					this.showBack = false;
				}
				// console.log('newVisibleTimeRange', newVisibleTimeRange, this.newSeries);
				// 获取最后一个数据点的时间
				// const lastDataPoint = this.areaSeries.lastValue();
				// const lastDataPointTime = lastDataPoint && lastDataPoint.time;
				// console.log('lastDataPoint', lastDataPoint);
			},

			subscribeCrosshairMove(param) {
				// console.log('param', param);
				if (param.point.x < 50) {
					// 加载老数据并更新图表
					console.log('滚动左侧了');
				}
			},
			//别的用户下单
			createOrder(data) {
				// console.log('data:::', data);
				let openOrder = localStorage.getItem('openOrder')
				if (openOrder == 'true') {
					const container = document.getElementById('mychart');
					const tdElement = document.querySelector(
						'#mychart .tv-lightweight-charts table tr:first-child td:nth-child(2) div');
					const toolTipWidth = this.myToolTip.width;
					const toolTipHeight = 70;
					const toolTipMargin = this.myToolTip.margin;
					// Create and style the tooltip html element
					const toolTip = document.createElement('div');
					// console.log('this.newSeries::', this.newSeries);
					toolTip.id = this.newSeries.time
					toolTip.setAttribute('price', this.newSeries.value || this.newSeries.close)
					toolTip.style =
						`width: 66px; height: 65px; position: absolute; box-sizing: border-box; font-size: 12px; text-align: left; z-index: 88; top: 12px; pointer-events: none; border-radius: 6px; padding: 4px;`;
					toolTip.style.background = data.type == 1 ? '#2DCC70' : '#FF5449';
					toolTip.style.color = '#fff';
					// toolTip.innerHTML = `<div style="font-size: 12px; margin: 4px 0px; display: flex; align-items:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
					// <img src="${data.avatar || require('@/assets/images/home/user.png')}" style="width:16px;margin-right: 5px" />
					// ${data.nickname}
					// </div>
					// <div style="display: flex; align-items:center;">
					// <img src="${data.type == 1 ? require('@/assets/images/home/zhang.png') : require('@/assets/images/home/die.png')}" style="width:16px;margin-right: 5px" />
					// ${data.amount}USDT
					// </div>
					// <div style="color: ${data.type == 1 ? '#2DCC70' : '#FF5449'}">
					// ${data.profit}USDT
					// </div>
					// `;
					toolTip.innerHTML = `
					<div class="otherOrder_el">
					<i class="el-icon-caret-top" style="position: absolute;left: 50%;top: -10px;font-size: 16px;transform: translateX(-50%); color: ${data.type == 1 ? '#2DCC70' : '#FF5449'}"></i>
					<div style="font-size: 12px; margin: 4px 0px; display: flex; align-items:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
					<img src="${data.avatar || require('@/assets/images/home/user.png')}" style="width:16px;margin-right: 5px" />
					${data.nickname}
					</div>
					<div style="display: flex; align-items:center;">
					${data.amount}USDT
					</div>
					<div style="display: flex; align-items:center;">
					${data.profit}USDT
					</div>
					<i class="el-icon-caret-bottom" style="position: absolute;left: 50%;bottom: -10px;font-size: 16px;transform: translateX(-50%); color: ${data.type == 1 ? '#2DCC70' : '#FF5449'}"></i>
					</div>
					`;
					tdElement.appendChild(toolTip);

					const chartBounds = this.chart.timeScale().getVisibleRange();
					// console.log('创建开始', this.newToTime);
					const coordinate = this.areaSeries.priceToCoordinate(this.newSeries.value || this.newSeries.close);
					const xCoordinate = this.chart.timeScale().timeToCoordinate(this.newSeries.time, chartBounds) - 33
					const coordinateY =
						coordinate - toolTipHeight > 0 ?
						coordinate - toolTipHeight :
						Math.max(
							0,
							Math.min(
								container.clientHeight - toolTipHeight,
								coordinate
							)
						);
					// console.log('coordinateY', coordinateY, coordinate, coordinate - toolTipHeight);
					this.toolTipList.push(this.newSeries.time)
					if (coordinate - toolTipHeight > 0) {
						const div = toolTip.querySelector('div')
						div.className = 'otherOrder_el'
						toolTip.style.top = coordinateY + 'px';
					} else {
						const div = toolTip.querySelector('div')
						div.className = 'otherOrder_el2'
						toolTip.style.top = coordinateY + 5 + 'px';
					}
					toolTip.style.left = this.tick != 'Tick' ? xCoordinate + 'px' : xCoordinate + 'px';
					// toolTip.style.top = coordinateY + 'px';
					// console.log('this.toolTipList', this.toolTipList);
					// 三秒后删除 dom
					setTimeout(() => {
						tdElement.removeChild(toolTip);
						let findIndex = this.toolTipList.findIndex(i => this.newSeries.time)
						this.toolTipList.splice(findIndex, 1)
						// console.log('this.toolTipList', this.toolTipList);
					}, 5000)
				}
				// console.log('弹框toolTip:::', toolTip, xCoordinate, coordinateY);
			},
			// 自己下单
			createMyOrder(data) {
				let myOrder = localStorage.getItem('myOrder')
				if (myOrder == 'true') {
					const container = document.getElementById('mychart');
					const tdElement = document.querySelector(
						'#mychart .tv-lightweight-charts table tr:first-child td:nth-child(2) div');
					// console.log('tdElement::', tdElement);
					const toolTipWidth = this.myToolTip.width;
					const toolTipHeight = this.myToolTip.height;
					const toolTipMargin = this.myToolTip.margin;
					// Create and style the tooltip html element
					const toolTip = document.createElement('div');
					toolTip.id = this.newSeries.time
					toolTip.setAttribute('price', this.newSeries.value || this.newSeries.close)
					toolTip.style =
						`width: 66px; height: 50px; position: absolute; font-size: 12px; text-align: left; z-index: 88; top: 12px; pointer-events: none; border-radius: 6px`;
					toolTip.style.color = data.type == 1 ? '#2DCC70' : '#FF5449';

					toolTip.innerHTML = `
					<div class="myOrder_el">
					<div style="width: 60px; height: 32px;background: #0E0E0F;border-radius: 16px;border: 1px solid; border-color: ${data.type == 1 ? '#2DCC70' : '#FF5449'}; text-align: center;line-height: 30px;">
						${data.amount}USDT
					</div>
				<div style="text-align: center;">
					<img src="${data.type == 1 ? require('@/assets/images/home/zhangC.png') : require('@/assets/images/home/dieC.png')}" style="width: 12px;" />
				</div>
				</div>
				`;
					// <div style="font-size: 12px; margin: 4px 0px; display: flex; align-items:center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; ">
					// 	<img src="${data.avatar || require('@/assets/images/home/user.png')}" style="width:16px;margin-right: 5px" />
					// 	${data.nickname}
					// </div>
					tdElement.appendChild(toolTip);

					const chartBounds = this.chart.timeScale().getVisibleRange();
					// console.log('创建开始', this.newSeries);
					const coordinate = this.areaSeries.priceToCoordinate(this.newSeries.value || this.newSeries.close);
					const xCoordinate = this.chart.timeScale().timeToCoordinate(this.newSeries.time, chartBounds) - 33
					// console.log('coordinate:::', coordinate, xCoordinate);
					// const coordinateY = coordinate > 70 ? coordinate + 50 : coordinate
					const coordinateY =
						coordinate - toolTipHeight > 0 ?
						coordinate - toolTipHeight :
						Math.max(
							0,
							Math.min(
								container.clientHeight - toolTipHeight,
								coordinate
							)
						);
					this.myToolTipList.push(this.newSeries.time)
					if (coordinate - toolTipHeight > 0) {
						const div = toolTip.querySelector('div')
						div.className = 'myOrder_el'
						toolTip.style.top = coordinateY + 12 + 'px';
					} else {
						const div = toolTip.querySelector('div')
						div.className = 'myOrder2_el'
						toolTip.style.top = coordinateY - 12 + 'px';
					}
					// console.log('创建完成', {
					// 	...data,
					// 	timestamp: this.newSeries.time,
					// });
					// console.log('coordinate', coordinate, coordinateY);
					toolTip.style.left = this.tick != 'Tick' ? xCoordinate + 'px' : xCoordinate + 'px';
					// toolTip.style.top = coordinateY + 'px';
				}
				// 时间用最新的 不用下单的时间 方便后续删除dom
				this.$store.commit('upDataMyDownOrder', {
					...data,
					timestamp: this.newSeries.time,
				})
			},
			//测试自己下单
			testMyOrder() {
				this.newSeries = this.initEchartsData[39]
				console.log('this.newSeries', this.newSeries);
				// this.createMyOrder({
				// 	type: 1,
				// 	amount: 10
				// })
				this.createOrder(this.orderInfo)
			},
			testAdd() {
				let obj;
				if (this.lastObj && this.lastObj.value) {
					this.lastObj = {
						value: String(Number(this.lastObj.value) + 1),
						time: this.lastObj.time + 10
					}
				} else {
					let last = this.initEchartsData[this.initEchartsData.length - 1]
					console.log('last', last);
					this.lastObj = {
						value: String(Number(last.value) + 1),
						time: last.time + 10
					}
				}
				console.log('lastObj', this.lastObj);
				this.areaSeries?.update(this.lastObj);
			},
			// 删除我自己下单的dom
			clearMyOrder(data) {

			},
			back() {
				this.chart.timeScale().scrollToRealTime()
				setTimeout(() => {
					// console.log('执行了》？');
					this.chart.timeScale().scrollToRealTime()
				}, 500)
			},
			areDecimalsSame(num) {
				// 将数字转换为字符串
				const numStr = num.toString();
				// 如果不是小数，直接返回 true
				if (numStr.indexOf('.') === -1) {
					return true;
				}
				// 获取小数点后的数字部分
				const decimalPart = numStr.split('.')[1];
				// 检查小数点后的数字是否都相同
				for (let i = 1; i < decimalPart.length; i++) {
					if (decimalPart[i] !== decimalPart[0]) {
						return false;
					}
				}
				return true;
			},
		},
		beforeDestroy() {
			closeSock()
		},

	}
</script>

<style scoped lang="less">
	.echart_box {
		position: relative;
		margin-bottom: 20px;
		overflow: hidden;
		margin-right: -5px;
		background-color: #fff;

		.back {
			position: absolute;
			left: calc(var(--timeWidth) - 135px);
			bottom: 30px;
			width: 36px;
			height: 36px;
			background-color: #262F42;
			z-index: 88;
			border: 1px solid #464B50;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

		}

		::v-deep .myOrder_el {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		::v-deep .myOrder2_el {
			display: flex;
			flex-direction: column-reverse;
			align-items: center;
		}

		::v-deep .otherOrder_el {
			.el-icon-caret-top {
				display: none;
			}
		}

		::v-deep .otherOrder_el2 {
			.el-icon-caret-bottom {
				display: none;
			}
		}
	}
</style>